<?php

namespace app\xs_attachment\controller\web;

use xsframe\base\AdminBaseController;
use xsframe\enum\SysSettingsKeyEnum;
use xsframe\facade\service\DbServiceFacade;
use xsframe\util\ArrayUtil;
use xsframe\util\FileUtil;
use xsframe\wrapper\AttachmentWrapper;

class Sets extends AdminBaseController
{
    public function account()
    {
        $accountSettings = $this->settingsController->getAccountSettings($this->uniacid, 'settings');

        if ($this->request->isPost()) {
            $settingsData = $this->params['data'] ?? [];

            $settingsData = ArrayUtil::customMergeArrays($accountSettings, $settingsData);
            $data['settings'] = serialize($settingsData);

            DbServiceFacade::name("sys_account")->updateInfo($data, ['uniacid' => $this->uniacid]);

            $this->settingsController->reloadAccountSettings($this->uniacid);

            /* 执行上传云存储 start */
            $attachmentPath = IA_ROOT . "/public/attachment/";
            $type = $this->params['type'];

            $attachmentController = new AttachmentWrapper();

            switch ($type) {
                case 'alioss':
                    $attachmentController->aliOss($this->params['key'], $this->params['secret'], $this->params['url'], $this->params['bucket']);
                    break;
                case 'qiniu':
                    $attachmentController->qiNiu($this->params['accesskey'], $this->params['secretkey'], $this->params['bucket']);
                    break;
                case 'cos':
                    $attachmentController->cos($this->params['appid'], $this->params['secretid'], $this->params['secretkey'], $this->params['bucket'], $this->params['local']);
                    break;
                case 'buckets':
                    $ret = $attachmentController->buckets($this->params['key'], $this->params['secret']);
                    show_json(1, ['data' => $ret]);
                    break;
                case 'upload_remote':
                    $uniacid = $this->params['uniacid'] ?? 0;
                    $setting = $this->settingsController->getSysSettings(SysSettingsKeyEnum::ATTACHMENT_KEY);
                    $attachmentController->fileDirRemoteUpload($setting, $attachmentPath, $attachmentPath . 'images' . ($uniacid > 0 ? '/' . $uniacid : ''));
                    break;
            }
            /* 执行上传云存储 end */

            $this->success();
        }

        $localAttachment = FileUtil::fileDirExistImage(IA_ROOT . "/public/attachment/" . 'images/' . $this->uniacid);

        $result = [
            'accountSettings'  => $accountSettings,
            'local_attachment' => $localAttachment,
            'postUrl'          => webUrl('sets/account'),
        ];
        return $this->template('account', $result);
    }
}
